helloApp.factory('requestInterceptor', function($q, $rootScope) {

    $rootScope.pendingRequests = 0;
    $rootScope.hasRequestError = false;
    $rootScope.hasResponseError = false;
    $rootScope.isDialogVisible = false;

	function updateLoadingDialog() {

		if ((!$rootScope.isDialogVisible) && ($rootScope.pendingRequests > 0)) {
        	$("#loadingDialog").modal();
        	$rootScope.isDialogVisible = true;
        } else {
			if (($rootScope.isDialogVisible) && ($rootScope.pendingRequests == 0)) {
				$("#loadingDialog").modal("hide");
				$(".modal-backdrop").remove();
				$rootScope.isDialogVisible = false;

				if (($rootScope.hasRequestError) || ($rootScope.hasResponseError)){
					alert("An error occured. Please try later.");
					$rootScope.hasRequestError = false;
                    $rootScope.hasResponseError = false;
				}
			}
		}
	}

	return {
		'request': function (config) {
			$rootScope.pendingRequests++;
			updateLoadingDialog();
			return config || $q.when(config);
		},

		'requestError': function(rejection) {
			$rootScope.pendingRequests--;
			$rootScope.hasRequestError = true;
			updateLoadingDialog();
			return $q.reject(rejection);
		},

		'response': function(response) {
			$rootScope.pendingRequests--;
			updateLoadingDialog();
			return response || $q.when(response);
		},

		'responseError': function(rejection) {
			$rootScope.pendingRequests--;
			$rootScope.hasResponseError = true;
			updateLoadingDialog();
			return $q.reject(rejection);
		}
	}
});

helloApp.config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('requestInterceptor');
}]);